package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.thread.AppThreadLocalUtil;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.freemarker.FreemarkerGenerator;
import com.heima.common.redis.CacheService;
import com.heima.file.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.SearchArticleVo;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private FreemarkerGenerator freemarkerGenerator;
    @Autowired
    private MinIoTemplate minIoTemplate;


    @Override
    public ResponseResult load(ArticleHomeDto dto) {
        //minBehotTime = 2063
        //publish_time < minBehotTime
        List<ApArticle> apArticles = apArticleMapper.loadArticle(dto, 1);
        return ResponseResult.okResult(apArticles);
    }

    @Override
    public ResponseResult loadmore(ArticleHomeDto dto) {
        //publish_time < minBehotTime
        List<ApArticle> apArticles = apArticleMapper.loadArticle(dto, 1);
        return ResponseResult.okResult(apArticles);
    }

    @Override
    public ResponseResult loadnew(ArticleHomeDto dto) {
        //publish_time > maxBehotTime
        List<ApArticle> apArticles = apArticleMapper.loadArticle(dto, 2);
        return ResponseResult.okResult(apArticles);
    }

    @Override
    @Async
    public void generate(Long articleId) {

        //查询ApArticleContent表，获得里面的content数据
        LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApArticleContent::getArticleId, articleId);
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(wrapper);
        if (apArticleContent == null) {
            log.warn("文章内容不存在");
            return;
        }

        //创建一个数据集合Map，把上一步content数据赋值到map的content字段上
        Map<String, Object> map = new HashMap<>(1);
        map.put("content", apArticleContent.getContent());

        //调用Freemarker插件，生成HTML页面
        InputStream is = freemarkerGenerator.generate("article.ftl", map);

        //调用MinIO插件，上传HTML页面
        String url = minIoTemplate.uploadFile("", articleId + ".html", is, "html");

        //更新ApArticle，修改里面Static_url字段
        ApArticle apArticle = apArticleMapper.selectById(articleId);
        if (apArticle == null) {
            log.warn("文章为空");
            return;
        }
        apArticle.setStaticUrl(url);
        apArticleMapper.updateById(apArticle);
    }


    /**
     * 保存app端相关文章
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseResult saveArticle(ArticleDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //组装article表数据
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);
        //判断是新增还是修改
        Long id = dto.getId();
        String content = dto.getContent();

        if (id == null) {
            //新增
            //插入article
            int insertResult = apArticleMapper.insert(apArticle);
            if (insertResult < 1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "新闻文章失败");
            }
            //组装articleconfig表数据
            //插入article_config表
            ApArticleConfig config = new ApArticleConfig();
            config.setIsDelete(false);
            config.setIsForward(true);
            config.setIsDown(false);
            config.setIsComment(true);
            config.setArticleId(apArticle.getId());
            int configResult = apArticleConfigMapper.insert(config);
            if (configResult < 1) {
                log.warn("文章配置表插入失败");
                throw new RuntimeException("配置表插入失败");
            }

            //插入article_content表
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setContent(content);
            apArticleContent.setArticleId(config.getId());
            int contentinsert = apArticleContentMapper.insert(apArticleContent);
            if (contentinsert < 1) {
                log.warn("文章内容表插入失败");
                throw new RuntimeException("内容表插入失败");
            }

            //调用线程的方法实现文章详情的生成和更新
            generate(apArticle.getId());


            return ResponseResult.okResult(apArticle.getId());
        } else {
            //id存在--修改
            //修改article
            int updateResult = apArticleMapper.updateById(apArticle);
            if (updateResult < 1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "文章内容修改失败");
            }
            //修改article_content表
            ApArticleContent updateContent = new ApArticleContent();
            updateContent.setContent(content);

            LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApArticleContent::getId, id);
            int updateContentResult = apArticleContentMapper.update(updateContent, wrapper);
            if (updateContentResult < 1) {
                log.warn("文章内容表修改失败");
                throw new RuntimeException("文章内容表修改失败");
            }

            //调用详情生成

            //将articleId返回
            return ResponseResult.okResult(id);
        }
    }

    //更新代码索引
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public void sendIndexUpdate(ApArticle apArticle, String content) {
        //article服务
        if (apArticle == null) {
            return;
        }
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle, vo);
        vo.setContent(content);
        kafkaTemplate.send("es.index.update", JSON.toJSONString(vo));
    }


    /**
     * 加载文章详情 数据回显
     *
     * @param dto
     * @return
     */
    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //出参   点赞 不喜欢 收藏 关注
        boolean isfollow = false;
        boolean islike = false;
        boolean isunlike = false;
        boolean iscollection = false;

        ApUser user = AppThreadLocalUtil.getUser();
        if (user != null) {
            //喜欢行为
            String likeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
            if (StringUtils.isNotBlank(likeBehaviorJson)) {
                islike = true;
            }
            //不喜欢行为
            String unLikeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
            if (StringUtils.isNotBlank(unLikeBehaviorJson)) {
                isunlike = true;
            }
            //是否收藏
            String collctionJson = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(), dto.getArticleId().toString());
            if (StringUtils.isNotBlank(collctionJson)) {
                iscollection = true;
            }
            //是否关注
            Double score = cacheService.zScore(BehaviorConstants.APUSER_FANS_RELATION + user.getId(), dto.getArticleId().toString());
            if (score != null) {
                isfollow = true;
            }


        }
        Map<String, Object> map = new HashMap<>();
        map.put("isfollow",isfollow);
        map.put("islike",islike);
        map.put("isunlike",isunlike);
        map.put("iscollection",iscollection);
        return ResponseResult.okResult(map);
    }


}
